package cn.edu.hubu.hubusmartzoohouse.service.impl;

import cn.edu.hubu.hubusmartzoohouse.entity.User;
import cn.edu.hubu.hubusmartzoohouse.mapper.UserMapper;
import cn.edu.hubu.hubusmartzoohouse.service.UserService;
import cn.edu.hubu.hubusmartzoohouse.vo.ResultVo;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public ResultVo checkAccount(String account) {
        //编写业务代码
        //1.调用UserMapper中的selectByAccount根据account参数查询用户信息
        User user = userMapper.selectByAccount(account);
        //2.判断查询结果并封装验证结果
        if(user!=null){
            return new ResultVo(500, "账号不可用！", account);
        } else {
            return new ResultVo(200, "账号可用！", account);
        }
    }

    @Override
    public ResultVo saveUser(User user) {
        //保存用户信息
        //1.将User对象的密码MD5加密
        //使用hutool包中的工具类进行加密
        String loginPwd = user.getLoginPwd(); //明文
        String newPwd = DigestUtil.md5Hex(loginPwd);
        user.setLoginPwd(newPwd);

        //2.保存用户
        int i = userMapper.insert(user);

        //3.根据注册结果进行响应
        if (i>0) {
            return new ResultVo(200, "注册成功！", null);
        } else {
            return new ResultVo(500, "注册失败！", null);
        }
    }

    @Override
    public ResultVo checkLogin(String account, String pwd) {
        User user = userMapper.selectByAccount(account);
        if(user==null){
            return new ResultVo(500, "账号错误，登录失败", null);
        }
        String newPwd = DigestUtil.md5Hex(pwd);
        String dbPwd = user.getLoginPwd(); //数据库存储的正确的密码
        if(newPwd.equals(dbPwd)){
            //登录成功
//            user.setLoginPwd("*********");
            return new ResultVo(200,"登录成功!", user);
        }else{
            //登录失败
            return new ResultVo(500, "密码错误1，登录失败", null);
        }
    }

}
